import axios from 'axios'
import store from '@/store'
import history from './history'
import { message } from 'antd'
import { logout } from '@/store/actions/login'

const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000
})


instance.interceptors.request.use(config => {
  const state = store.getState()
  if (state.user.token) {
    config.headers.Authorization = `Bearer ${state.user.token}`
  }
  return config
}, e => Promise.reject(e))

instance.interceptors.response.use(res => {
  return res?.data?.data || res
}, e => {
  if (e.response.status === 401) {
    message.error('登录失效')
    store.dispatch(logout())
    if ( history.location.pathname !== '/login') {
      history.push({
        pathname: '/login',
        state: { returnUrl: history.location.pathname }
      })
    }
  }
  Promise.reject(e)
})

export default instance